package com.example.springbootbatch.validator;

import org.springframework.batch.item.validator.ValidationException;
import org.springframework.batch.item.validator.Validator;
import org.springframework.beans.factory.InitializingBean;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * 自定义校验器
 * @author ljw
 * @date 2022/8/31 7:34
 */
public class CsvBeanValidator<T> implements Validator<T>, InitializingBean {

    //验证器
    private javax.validation.Validator validator;


    /**
     * 使用 JSR-30 的 Validator 来校验我们的数据，在此处进行初始化
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.usingContext().getValidator();
    }

    /**
     * 验证方法
     */
    @Override
    public void validate(T value) throws ValidationException {
        //验证数据
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(value);

        if (constraintViolations.size() > 0) {
            StringBuilder message = new StringBuilder();
            for (ConstraintViolation<T> constraintViolation : constraintViolations) {
                message.append(constraintViolation.getMessage()+"\n");
            }
            throw new ValidationException(message.toString());
        }
    }
}
